package com.atguigu.flink.chapter5.sink;

import com.alibaba.fastjson.JSON;
import com.atguigu.flink.WaterSensor;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2020/12/21 11:09
 */
public class Flink02_Sink_Redis {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        FlinkJedisPoolConfig conf = new FlinkJedisPoolConfig.Builder()
          .setHost("hadoop162")
          .setPort(6379)
          .setMaxTotal(100)
          .setTimeout(10000)
          .setMaxIdle(10)
          .build();
        env
          .socketTextStream("hadoop162", 9999)
          .map(line -> {
              String[] split = line.split(",");
              return new WaterSensor(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
          })
          .keyBy(WaterSensor::getId)
          .sum("vc")
          .addSink(new RedisSink<>(conf, new RedisMapper<WaterSensor>() {
              @Override
              public RedisCommandDescription getCommandDescription() {
                  // set hset sadd ...
                  // 你使用的命令  最外层的key
                  return new RedisCommandDescription(RedisCommand.HSET, "sensor");
              }

              @Override
              public String getKeyFromData(WaterSensor data) {
                  // 指的的是Hash的那个field
                  return data.getId();
              }

              @Override
              public String getValueFromData(WaterSensor data) {
                  // hash的value
                  return JSON.toJSONString(data);
              }
          }));
        env.execute();
    }
}
/*
hash:
key             value(hash)
"sensor"        field           value
                "sensor_1"     {"", "", ..}

 */